class GuaAnimation {
    constructor(game, animation, name) {
        // log(animation, name)
        let a = animation
        this.game = game
        this.animations = {}
        for (let action of a.actions) {
            this.animations[action.name] = []

            for (let i = 0; i < action.numberOfFrames; i++) {
                let index = '0'.repeat(String(action.numberOfFrames).length - String(i).length) + String(i)
                // log('index', index)
                let key = a.name + action.name + index
                // log('key', key)
                let t = game.textureByName(key)
                // log('t', t)
                this.animations[action.name].push(t)
                // log('this.animations', this.animations)
            }
        }

        this.animationName = name || a.actions[0].name
        log('this.animationName', this.animationName)
        // log('this.animationName', this.animationName)
        // log('this.frames()', this.frames())
        this.texture = this.frames()[0]
        this.w = this.texture.width
        this.h = this.texture.height
        this.frameIndex = 0
        this.frameCount = this.frames().length
        this.flipX = false
    }

    static new(...args) {
        return new this(...args)
    }

    frames() {
        return this.animations[this.animationName]
    }

    draw() {
        let context = this.game.context
        if (this.flipX) {
            context.save()
            let x = this.x + this.w / 2
            context.translate(x, 0)
            context.scale(-1, 1)
            context.translate(-x, 0)
            context.drawImage(this.texture, this.x, this.y)
            context.restore()
        } else {
            context.drawImage(this.texture, this.x, this.y)
        }
    }

    updateFrame() {
        this.frameCount--
        if (this.frameCount == 0) {
            this.frameCount = 3
            this.frameIndex = (this.frameIndex + 1) % this.frames().length
            this.texture = this.frames()[this.frameIndex]
        }

    }

    update() {
        this.updateFrame()
    }

    changeAnimation(name) {
        this.animationName = name
    }

    remove() {
        this.game.scene.removePlant(this)
    }

}